<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
  </head>
  <body>
  
    
    <script>
       //  手写redux ,状态管理器
      // store , reducer , state ,dispatch , action
     
    //  function store(obj){      
    //   let states = {
    //      ...obj
    //   };
    //     return {
    //       dispatch(action){
    //          if(action.type == 'add'){
    //           states[action.name] = states[action.name] ++;
    //          }

    //          if(action.type == 'update' && action.name =='name'){
    //           states[action.name] = action.payload;
    //         }
    //          return states[action.name];
    //         }     
    //     }
    //  }
    
    // let states = store({ num: 2, name:"yht"});
    // let num = states.dispatch({type:"add", name:"num"});
    // let name = states.dispatch({type:"update", name:"name" , payload:"ht"});
    // console.log(num, name);

     // 上面这么写非常的耦合，而且 reducer 处理函数应该是高度和state 相关的，也就是应该写在外面额不是里面改写

      function createStore(states, reducers){
        return {
          dispatch(action){
            var reducer =  reducers.find(function(v,i){
              var funName = v.name;
              var reducerName = funName.substring(0, funName.length - 7);
              var actionName = action.type.substring(0, action.type.length - 7);
              return reducerName == actionName;
            });
              return reducer(states, action);
          }
        }
      }

     let states = { name:"yht" , age:"20"};
     let store = createStore(states , [nameReducer, ageReducer]);

     states = store.dispatch({type:"name/update", payload:"hhhh "});
        console.log(states);
    states = store.dispatch({type:"age/update", payload:666});
    console.log(states);
     // 新值覆盖旧值， nameReducer 函数只关心name， ageReducer 只关心age 
     function nameReducer(state, action){
      if (action.type === 'name/update') {
          // 如果是，复制 `state`
          return {
            ...state,
            // 使用新值更新 state 副本
            name: action.payload
          }
        }
        return state
     }
      
     function ageReducer(state, action){
      if (action.type === 'age/update') {
          // 如果是，复制 `state`
          return {
            ...state,
            // 使用新值更新 state 副本
            age: action.payload
          }
        }
        return state
     }
    
      
    
    
    </script>
  </body>
</html>